import 'package:flutter/material.dart';
import 'dart:math' as math;

class BookPageFlip extends StatefulWidget {
  final Widget child;
  final VoidCallback? onFlipComplete;
  final bool isForward;
  final Duration duration;

  const BookPageFlip({
    super.key,
    required this.child,
    this.onFlipComplete,
    this.isForward = true,
    this.duration = const Duration(milliseconds: 800),
  });

  @override
  State<BookPageFlip> createState() => _BookPageFlipState();
}

class _BookPageFlipState extends State<BookPageFlip>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _flipAnimation;
  late Animation<double> _bendAnimation;
  late Animation<double> _shadowAnimation;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: widget.duration, vsync: this);

    // 翻页动画
    _flipAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOutCubic),
    );

    // 页面弯曲动画
    _bendAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.0, 0.8, curve: Curves.easeInOut),
      ),
    );

    // 阴影动画
    _shadowAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.1, 0.9, curve: Curves.easeInOut),
      ),
    );

    // 缩放动画
    _scaleAnimation = Tween<double>(begin: 1.0, end: 0.95).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOutCubic),
    );

    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        widget.onFlipComplete?.call();
      }
    });

    // 自动开始动画
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Stack(
          children: [
            // 原始页面（底层）
            Transform(
              alignment:
                  widget.isForward
                      ? Alignment.centerLeft
                      : Alignment.centerRight,
              transform:
                  Matrix4.identity()
                    ..setEntry(3, 2, 0.001)
                    ..rotateY(
                      widget.isForward
                          ? -_flipAnimation.value * math.pi
                          : (1 - _flipAnimation.value) * math.pi,
                    )
                    ..scale(_scaleAnimation.value),
              child: Container(
                decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withAlpha((25).toInt()),
                      blurRadius: 5,
                      offset: const Offset(2, 2),
                    ),
                  ],
                ),
                child: widget.child,
              ),
            ),
            // 翻页效果（上层）
            if (_flipAnimation.value > 0.05 && _flipAnimation.value < 0.95)
              Positioned.fill(
                child: Transform(
                  alignment:
                      widget.isForward
                          ? Alignment.centerLeft
                          : Alignment.centerRight,
                  transform:
                      Matrix4.identity()
                        ..setEntry(3, 2, 0.001)
                        ..rotateY(
                          widget.isForward
                              ? -_flipAnimation.value * math.pi
                              : (1 - _flipAnimation.value) * math.pi,
                        ),
                  child: _buildFlippingPage(),
                ),
              ),
          ],
        );
      },
    );
  }

  Widget _buildFlippingPage() {
    final flipProgress = _flipAnimation.value;
    final bendProgress = _bendAnimation.value;
    final shadowProgress = _shadowAnimation.value;

    // 计算弯曲程度
    final bendAmount = math.sin(bendProgress * math.pi) * 0.1;

    // 计算阴影位置和强度
    final shadowOffset =
        widget.isForward ? -20 * shadowProgress : 20 * shadowProgress;
    final shadowOpacity = 0.3 * shadowProgress;

    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft:
              widget.isForward
                  ? Radius.circular(20 * bendProgress)
                  : Radius.zero,
          bottomLeft:
              widget.isForward
                  ? Radius.circular(20 * bendProgress)
                  : Radius.zero,
          topRight:
              widget.isForward
                  ? Radius.zero
                  : Radius.circular(20 * bendProgress),
          bottomRight:
              widget.isForward
                  ? Radius.zero
                  : Radius.circular(20 * bendProgress),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha((shadowOpacity * 255).toInt()),
            blurRadius: 25 * shadowProgress,
            offset: Offset(shadowOffset, 0),
          ),
          // 页面边缘阴影
          BoxShadow(
            color: Colors.black.withAlpha((25 * shadowProgress).toInt()),
            blurRadius: 5,
            offset: Offset(widget.isForward ? -2 : 2, 0),
          ),
        ],
        gradient: LinearGradient(
          begin:
              widget.isForward ? Alignment.centerRight : Alignment.centerLeft,
          end: widget.isForward ? Alignment.centerLeft : Alignment.centerRight,
          colors: [Colors.white, Colors.grey.shade100, Colors.grey.shade200],
          stops: [0.0, 0.7, 1.0],
        ),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.only(
          topLeft:
              widget.isForward
                  ? Radius.circular(20 * bendProgress)
                  : Radius.zero,
          bottomLeft:
              widget.isForward
                  ? Radius.circular(20 * bendProgress)
                  : Radius.zero,
          topRight:
              widget.isForward
                  ? Radius.zero
                  : Radius.circular(20 * bendProgress),
          bottomRight:
              widget.isForward
                  ? Radius.zero
                  : Radius.circular(20 * bendProgress),
        ),
        child: Transform(
          transform:
              Matrix4.identity()
                ..setEntry(3, 2, 0.001)
                ..rotateY(bendAmount),
          child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin:
                    widget.isForward
                        ? Alignment.centerRight
                        : Alignment.centerLeft,
                end:
                    widget.isForward
                        ? Alignment.centerLeft
                        : Alignment.centerRight,
                colors: [
                  Colors.white.withAlpha(
                    ((1 - flipProgress * 0.3) * 255).toInt(),
                  ),
                  Colors.grey.shade50.withAlpha(
                    ((1 - flipProgress * 0.5) * 255).toInt(),
                  ),
                ],
              ),
            ),
            child: Opacity(
              opacity: 1 - flipProgress * 0.8,
              child: widget.child,
            ),
          ),
        ),
      ),
    );
  }
}

// 更高级的翻书效果，包含页面弯曲和阴影
class AdvancedBookFlip extends StatefulWidget {
  final Widget child;
  final VoidCallback? onFlipComplete;
  final bool isForward;
  final Duration duration;

  const AdvancedBookFlip({
    super.key,
    required this.child,
    this.onFlipComplete,
    this.isForward = true,
    this.duration = const Duration(milliseconds: 1000),
  });

  @override
  State<AdvancedBookFlip> createState() => _AdvancedBookFlipState();
}

class _AdvancedBookFlipState extends State<AdvancedBookFlip>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _flipAnimation;
  late Animation<double> _bendAnimation;
  late Animation<double> _shadowAnimation;
  late Animation<double> _pageShadowAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: widget.duration, vsync: this);

    _flipAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOutCubic),
    );

    _bendAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.0, 0.7, curve: Curves.easeInOut),
      ),
    );

    _shadowAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.1, 0.8, curve: Curves.easeInOut),
      ),
    );

    _pageShadowAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: const Interval(0.3, 0.9, curve: Curves.easeInOut),
      ),
    );

    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        widget.onFlipComplete?.call();
      }
    });

    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Stack(
          children: [
            // 底层页面
            Transform(
              alignment:
                  widget.isForward
                      ? Alignment.centerLeft
                      : Alignment.centerRight,
              transform:
                  Matrix4.identity()
                    ..setEntry(3, 2, 0.001)
                    ..rotateY(
                      widget.isForward
                          ? -_flipAnimation.value * math.pi
                          : (1 - _flipAnimation.value) * math.pi,
                    ),
              child: Container(
                decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withAlpha((25).toInt()),
                      blurRadius: 8,
                      offset: const Offset(3, 3),
                    ),
                  ],
                ),
                child: widget.child,
              ),
            ),
            // 翻页效果
            if (_flipAnimation.value > 0.02 && _flipAnimation.value < 0.98)
              Positioned.fill(child: _buildAdvancedFlippingPage()),
            // 页面阴影
            if (_pageShadowAnimation.value > 0)
              Positioned(
                left: widget.isForward ? null : 0,
                right: widget.isForward ? 0 : null,
                top: 0,
                bottom: 0,
                child: Container(
                  width: 60,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin:
                          widget.isForward
                              ? Alignment.centerRight
                              : Alignment.centerLeft,
                      end:
                          widget.isForward
                              ? Alignment.centerLeft
                              : Alignment.centerRight,
                      colors: [
                        Colors.black.withAlpha(
                          (0.15 * _pageShadowAnimation.value * 255).toInt(),
                        ),
                        Colors.transparent,
                      ],
                    ),
                  ),
                ),
              ),
          ],
        );
      },
    );
  }

  Widget _buildAdvancedFlippingPage() {
    final flipProgress = _flipAnimation.value;
    final bendProgress = _bendAnimation.value;
    final shadowProgress = _shadowAnimation.value;

    // 更复杂的弯曲计算
    final bendAmount = math.sin(bendProgress * math.pi) * 0.15;
    final cornerRadius = 25 * bendProgress;

    return Transform(
      alignment:
          widget.isForward ? Alignment.centerLeft : Alignment.centerRight,
      transform:
          Matrix4.identity()
            ..setEntry(3, 2, 0.001)
            ..rotateY(
              widget.isForward
                  ? -flipProgress * math.pi
                  : (1 - flipProgress) * math.pi,
            ),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
            topLeft:
                widget.isForward ? Radius.circular(cornerRadius) : Radius.zero,
            bottomLeft:
                widget.isForward ? Radius.circular(cornerRadius) : Radius.zero,
            topRight:
                widget.isForward ? Radius.zero : Radius.circular(cornerRadius),
            bottomRight:
                widget.isForward ? Radius.zero : Radius.circular(cornerRadius),
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withAlpha((shadowProgress * 4 * 255).toInt()),
              blurRadius: 30 * shadowProgress,
              offset: Offset(
                widget.isForward ? -25 * shadowProgress : 25 * shadowProgress,
                0,
              ),
            ),
            BoxShadow(
              color: Colors.black.withAlpha((shadowProgress * 2 * 255).toInt()),
              blurRadius: 10,
              offset: Offset(widget.isForward ? -5 : 5, 0),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.only(
            topLeft:
                widget.isForward ? Radius.circular(cornerRadius) : Radius.zero,
            bottomLeft:
                widget.isForward ? Radius.circular(cornerRadius) : Radius.zero,
            topRight:
                widget.isForward ? Radius.zero : Radius.circular(cornerRadius),
            bottomRight:
                widget.isForward ? Radius.zero : Radius.circular(cornerRadius),
          ),
          child: Transform(
            transform:
                Matrix4.identity()
                  ..setEntry(3, 2, 0.001)
                  ..rotateY(bendAmount),
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin:
                      widget.isForward
                          ? Alignment.centerRight
                          : Alignment.centerLeft,
                  end:
                      widget.isForward
                          ? Alignment.centerLeft
                          : Alignment.centerRight,
                  colors: [
                    Colors.white.withAlpha((flipProgress * 255).toInt()),
                    Colors.grey.shade100.withAlpha(
                      (flipProgress * 255).toInt(),
                    ),
                    Colors.grey.shade200.withAlpha(
                      (flipProgress * 255).toInt(),
                    ),
                  ],
                  stops: [0.0, 0.6, 1.0],
                ),
              ),
              child: Opacity(
                opacity: 1 - flipProgress * 0.9,
                child: widget.child,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
